var express = require('express');
var router = express.Router();
let db = require('../tools/Db');
let to = require('../tools/to');
let {secret} = require('../tools/config');
let jwt = require('jsonwebtoken');

//根据cid获取课程的详情
router.get('/coursedetail',async(req,res,next)=>{
    //获取cid
    let cid = req.query.cid;
    //根据cid去查询课程的详情
    let sql1 = `SELECT
	a.cid,
	a.area_name,
	a.category_name,
	a.intro as courseIntro,
	a.image_src,
	a.title,
	a.price,
    a.grade_name,
	b.realname,
	b.intro as teacherIntro,
	b.head_photo_url
    FROM
	e_course AS a
    LEFT JOIN e_teacher AS b ON a.tid = b.tid`
    // let [err,result] = await to(db.query(sql1,[cid]));
    let sql2 = `select * from e_video where cid=?`;
    // let b = await db.query(sql2,[cid]);

    //将两次查询的数组包在一个数组中，利用解构赋值提取出来
    //两次查询可以同时进行，提高了查询效率，Promise.all()方法适用于同时进行异步操作的场景
    Promise.all([
        db.query(sql1,[cid]),
        db.query(sql2,[cid])
    ]).then((data)=>{
        console.log(data);
        let[course,video] = data;
        course[0].video = video;
        res.json({code:200,data:course[0],msg:'课程详情数据发送成功'})
    }).catch((err)=>{
        next(err);
    })

    // let data = result[0];
    // data.video = b;
    // console.log(data);
})

//视频播放
//cid 课程id
//vnum 该课程下的视频序号
router.get('/videoplay',(req,res,next)=>{
    console.log(req.headers);
    let {token=''} = req.headers;
    if(!token){
        res.json({code:205,data:null,msg:'token为空，请登录'});
        return;
    }
    //验证token的有效性
    jwt.verify(token,secret,async(err,encode)=>{
        //验证失败，err返回错误消息
        //验证成功，encode为payload对象
        if(!err){
            //进一步验证时间有效性
            if(Date.now() > encode.exp){
                res.json({code:205,data:null,msg:'token已失效，请重新登录'})
                return;
            }else{
                //token还在有效期，可以提供接口服务
                let{cid,vnum} = req.query;
                let sql = "select * from e_video where cid=? and vnum=?";
                let [err,result] = await to(db.query(sql,[cid,vnum]));
                if(!err){
                    res.json({code:200,data:result,msg:'视频数据获取成功'});
                }else{
                    next(err);
                }
            }
        }else{
            res.json({code:205,data:null,msg:'token无效，请登录'});
            return;
        }
    })

    
})

module.exports = router;